import electron, {app, protocol, BrowserWindow, ipcMain, BrowserView, net, session} from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'

import installExtension, {VUEJS_DEVTOOLS} from 'electron-devtools-installer'

const isDevelopment = process.env.NODE_ENV !== 'production'

protocol.registerSchemesAsPrivileged([
    {scheme: 'app', privileges: {secure: true, standard: true}}
])

// 需要拦截的URL地址
const url_filter = {
    urls: ["https://adminweb.cashpocket8.com/api/api/system/system_version",
        "https://adminweb.plumpwallet8.com/api/api/system/system_version",
        "https://adminweb.treeloan6.com/api/api/system/system_version",
        "https://adminweb.loannow50.com/api/api/system/system_version",
        "https://admin.in-come.in/cashloan/d/role/getmenu",
        "https://cms.cashbar.in/query_user_info",
        "http://adminweb.cashfish.cc/api/user/auth_list",
        "https://cbcash-call.cashbu4.com/index.php?r=main/home",
        "https://cbcash-call.cashbu4.com/index.php",
        "https://cbcash-call.cashbu4.com/css/site.css",
        "https://cbcash-call.cashbu4.com/index.php?r=main/login",
        "https://ok-call.moneywoods.in/index.php?r=main/home",
        "https://ok-call.moneywoods.in/index.php",
        "https://ok-call.moneywoods.in/css/site.css",
        "https://ok-call.moneywoods.in/index.php?r=main/login",
        "https://lendking-call.moneywoods.in/index.php?r=main/home",
        "https://lendking-call.moneywoods.in/index.php",
        "https://lendking-call.moneywoods.in/css/site.css",
        "https://lendking-call.moneywoods.in/index.php?r=main/login",
    ]
}


let win;
let accountWin;
let viewRight;
let viewLeft;
let viewBar;
let viewAccount;
let screenWidth
let currentAccount;
const userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.3809.131 Safari/537.36';


const Menu = electron.Menu

async function twoViews() {
    // const {width, height} = screen.getPrimaryDisplay().workAreaSize
    screenWidth = 1200;
    Menu.setApplicationMenu(null)
    win = new BrowserWindow({
        width: screenWidth,
        height: 800,
        title: "Collection",
        // frame:false,
        resizable: false
    })

    viewBar = new BrowserView({
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false
        }
    })

    win.addBrowserView(viewBar)
    viewBar.setBounds({x: 0, y: 0, width: 50, height: 800})
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        viewBar.webContents.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "#/ToolBar")
    } else {
        viewBar.webContents.loadURL('app://./index.html#ToolBar')
    }


    viewLeft = new BrowserView({
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false
        }
    })

    win.addBrowserView(viewLeft)
    viewLeft.setBounds({x: 50, y: 0, width: 300, height: 800})
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        viewLeft.webContents.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "#/left")
    } else {
        viewLeft.webContents.loadURL('app://./index.html#left')
    }
    viewLeft.webContents.openDevTools();


    session.defaultSession.webRequest.onBeforeSendHeaders(url_filter, (details, callback) => {
        viewLeft.webContents.send("token-message", {
            "adminToken": details.requestHeaders['X-ADMIN-TOKEN'],
            "token": details.requestHeaders['token'],
            "tm": details.requestHeaders['tm'],
            "cookie": details.requestHeaders['Cookie'],
            "authorization": details.requestHeaders['Authorization'] === undefined ? details.requestHeaders['authorization'] : details.requestHeaders['Authorization'],
        })
    })

    win.on('close', e => {
        win = null
        accountWin = null
        // if (viewRight!==null){
        //     viewRight.webContents.session.clearStorageData()
        // }
        app.exit();
    });
}

ipcMain.on('initWindow', (event, arg) => {
    viewRight = new BrowserView({
        webPreferences: {
            webSecurity: false,
            nodeIntegration: true,
            contextIsolation: false,

        },
    })
    viewRight.webContents.session.clearStorageData()
    viewRight.webContents.session.clearCache()

    win.addBrowserView(viewRight)
    viewRight.setBounds({x: 350, y: 0, width: 850, height: 800})
    viewRight.webContents.loadURL(arg, {userAgent: userAgent})
    // viewRight.webContents.openDevTools();
})
ipcMain.on('createNewWindow', (event, arg) => {
    win.removeBrowserView(viewRight)
    viewRight = new BrowserView({
        webPreferences: {
            webSecurity: false,
            nodeIntegration: true,
            contextIsolation: false,

        },
    })
    viewRight.webContents.session.clearStorageData()
    viewRight.webContents.session.clearCache()

    win.addBrowserView(viewRight)
    viewRight.setBounds({x: 350, y: 0, width: 850, height: 800})
    viewRight.webContents.loadURL(arg, {userAgent: userAgent})
    // viewRight.webContents.openDevTools();
})

ipcMain.on('logout-dialog-remove', (event, arg) => {
    if (win !== null && typeof win !== "undefined") {
        win.close();
    }
})

ipcMain.on('account-tab', (event, arg) => {
    if (accountWin !== null && typeof accountWin !== "undefined") {
        accountWin.moveTop();
    }else {
        accountWin = new BrowserWindow({
            width: 1200,
            height: 800,
            title: "Account List",
            // frame:false,
            resizable: false
        })
        viewAccount = new BrowserView({
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
                webSecurity: false
            }
        })
        accountWin.addBrowserView(viewAccount)
        viewAccount.setBounds({x: 0, y: 0, width: 1200, height: 800})
        if (process.env.WEBPACK_DEV_SERVER_URL) {
            viewAccount.webContents.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "#/AccountList")
        } else {
            viewAccount.webContents.loadURL('app://./index.html#AccountList')
        }
        // viewAccount.webContents.openDevTools();
    }
    accountWin.on('close', e => {
        accountWin = null
    });
})


// Quit when all windows are closed.
app.on('window-all-closed', () => {
    //console.log("== 退出electron ===");
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    app.quit()
    // if (process.platform !== 'darwin') {
    // }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
            await installExtension(VUEJS_DEVTOOLS)
        } catch (e) {
            //console.error('Vue Devtools failed to install:', e.toString())
        }
    }
    // loginViews()
    twoViews();
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}




